<template>
  <div class="app-container">
    <zl-table ref="table" url="/sys/attach/list" :param.sync="par" :default-sort="{prop:'updateDt',order:'descending'}">
      <template slot="search">
        <el-form :inline="true" :model="par" class="left">
          <el-form-item label="文件名">
            <el-input v-model="par.fileName" clearable placeholder="请输入" />
          </el-form-item>
          <el-form-item label="文件后缀">
            <el-input v-model="par.prefix" clearable placeholder="请输入" />
          </el-form-item>
          <el-form-item label="是否公开">
            <el-select v-model="par.isPub" placeholder="请选择" clearable>
              <el-option label="是" :value="1" />
              <el-option label="否" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="所属用户">
            <UserSelect/>
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" type="primary" size="small" @click="query">搜 索</el-button>
          </el-form-item>
        </el-form>
      </template>
      <template slot="toolbar">
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-button size="small" plain type="primary" icon="el-icon-plus" @click="addAttach">新 增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button size="small" plain type="danger" icon="el-icon-delete" @click="deleteRows">删 除</el-button>
          </el-col>
        </el-row>
      </template>
      <template slot="cols">
        <el-table-column align="center" width="50px" type="index" :index="indexMethod" />
        <el-table-column align="center" type="selection" width="50"/>
        <el-table-column prop="value" label="" width="40px" align="center">
          <template slot-scope="scope">
            <i v-if="scope.row.isPub!==1" class="el-icon-lock"></i>
          </template>
        </el-table-column>
        <el-table-column min-width="150px" prop="fileName" label="文件名" show-overflow-tooltip sortable="custom">
          <template slot-scope="scope">
            <a class="main-color point filename" @click="downloadFile(scope.row)">{{ scope.row.fileName }}</a>
          </template>
        </el-table-column>
        <el-table-column prop="fileSize" label="文件大小" width="160px" show-overflow-tooltip align="center"/>
        <el-table-column prop="sourceName" label="来源" width="150px" show-overflow-tooltip align="center" />
        <el-table-column prop="md5" label="md5值" width="180px" show-overflow-tooltip />
        <el-table-column prop="description" label="文件描述" width="150px" show-overflow-tooltip />
        <el-table-column prop="createDt" label="创建日期" width="150px" show-overflow-tooltip align="center" sortable="custom"/>
        <el-table-column prop="updateDt" label="修改日期" width="150px" show-overflow-tooltip align="center" sortable="custom"/>

        <el-table-column align="center" label="操作" width="100px">
          <template slot-scope="scope">
            <el-button
            
              title="编辑"
              type="primary"
              circle
              plain
              class="el-icon-edit"
              size="mini"
              @click.native.prevent="editRow(scope.$index, scope.row)"
            />
          </template>
        </el-table-column>
      </template>
    </zl-table>
    <el-dialog :title="title" :visible.sync="show" :append-to-body="true" :close-on-click-modal="false" width="500px">
      <el-form ref="editForm" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="原附件" v-if="type===0">
          <a class="main-color point filename" @click="downloadFile(form)">{{ form.fileName }}</a>
        </el-form-item>
        <el-form-item label="选择附件" prop="fileIds" :class="{'is-required': type===1}">
          <Uploader ref="uploader" text="选择文件" v-model="form.fileIds" @finish="changeUpload">
          </Uploader>
        </el-form-item>
        <el-form-item label="所属用户" prop="userId" v-if="type===1">
          <el-input v-model="form.userId" clearable autocomplete="off" maxlength="50" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="是否公开" prop="isPub">
          <el-switch v-model.trim="isPub" active-color="#409EFF" inactive-color="#ff4949" class="mr5" />
          <span>{{ isPub ?'公开' : '私人' }}</span>
        </el-form-item>
        <el-form-item label="来源" prop="source">
          <el-select v-model="form.source" placeholder="请选择" clearable>
            <el-option label="消息附件" value="msg" />
            <el-option label="用户头像" value="head" />
            <el-option label="版本文件" value="ver" />
            <el-option label="试卷封面" value="exam_cover" />
          </el-select>
        </el-form-item>
        <el-form-item label="来源值" prop="sourceId">
          <el-input v-model="form.sourceId" clearable autocomplete="off" maxlength="50" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="附件说明" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :autosize="{minRows:3,maxRows:4}"
            clearable
            autocomplete="off"
            placeholder="请输入描述"
            maxlength="50"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" :loading="loading" @click="saveAttach">保 存</el-button>
        <el-button size="small" @click="show = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import { getToken } from '@/utils/auth'

import permission from '@/directive/right/right'
import { validator } from '@/utils/form'
import request from '@/utils/request'
import ZlTable from '@/components/table/table-con'
import UserSelect from '@/components/tag/user-select'
import Uploader from '@/components/Uploader/uploader'
import { deleteAttach } from '@/api/attach'
export default {
  name: 'Attachment',
  components: { ZlTable,Uploader,UserSelect },
  directives: { permission },
  data() {
    return {
      par: {
        prefix: '',
        isPub: null,
        fileName: ''
      },
      form: {
        id: null, isPub: 1, userId: null, description: null,source: null, sourceId: null,fileIds: []
      },
      isPub: true,
      type: 0,
      title: '修改附件',
      loading: false,
      show: false,
      rawFile: [],
      fileList: []
    }
  },
  computed: {
    token() {
      return {
        appToken: getToken()
      }
    },
    accept(){
      const arr = this.cfg.acceptType.split(',')||'jpg'
      for (let i = 0; i < arr.length; i++) {
        if(this.$util.isNotBlank(arr[i])){
          arr[i] = '.' + arr[i]
        }
      }
      return arr.join(',')
    },
    rules() {
      return {
        fileIds: [
          { validator: validator(this.validatorFile), message: '附件不能为空', trigger: ['blur', 'change'] }
        ],
        sourceId: [
          { validator: validator('integer_empty'), message: '来源值请输入数值', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  mounted() {

  },
  methods: {
    validatorFile(){
      if(this.type === 1){
        return this.form.fileIds instanceof Array && this.form.fileIds.length > 0
      }
      return true
    },
    getUrl(){
      let p1 = '/sys/attach/'
      let p2 = this.type === 0 ? 'update' : 'add'
      return p1 + p2
    },
    changeUpload(){
      this.$refs.editForm.validateField(['fileIds'])
      console.log(this.form)
    },
    saveAttach() {
      this.$refs.editForm.validate(r => {
        if (r) {
          console.log('pass')
          this.loading = true
          request({
            url: this.getUrl(), method: 'post', data: this.form
          }).then((r) => {
            this.$message.success('保存成功')
            this.loading = false
            this.show = false
            this.query()
          }).catch(() => {
            this.loading = false
          })
        }
      })
    },
    deleteRows() {
      const l = this.$refs.table.getSelected()
      if (l.length === 0) {
        this.$message.warning('请选择附件')
        return
      }
      this.$confirm('确定要删除选中的附件吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
      }).then(() => {
        deleteAttach(l.map(o => o.id)).then((r) => {
          this.$message.success('删除成功')
          this.query()
        })
      })
    },
    addAttach() {
      this.title = '新增附件'
      this.show = true
      this.type = 1
      this.form = { fileIds:[],isPub: 1 }
      this.isPub = true
      this.$nextTick(() => {
        this.$refs.uploader.clearFile()
        this.$refs.editForm.clearValidate()
      })
    },
    editRow(index, row) {
      this.title = '修改附件'
      console.log(row)
      this.type = 0
      this.form = this.$util.copy(row)
      this.isPub = row.isPub==1
      this.form.fileIds = []
      this.show = true
      this.$nextTick(() => {
        this.$refs.editForm.clearValidate()
      })
    },
    downloadFile(row){
      this.download('/sys/attach/download',{id:row.id},row.fileName)
    },
    query() {
      this.$refs.table.query()
    },
    indexMethod(index) {
      return (this.$refs.table.pageNum - 1) * this.$refs.table.pageSize + index + 1
    }
  },
  watch:{
    'isPub': function(v){
      this.form.isPub = v ? 1 : 0
    }
  }
}
</script>
<style scoped lang="scss">
::v-deep .filename{
  text-decoration: underline;
}

</style>
